﻿using System.Collections.Generic;
using System.Linq;

namespace SharePointUtilitiesForDevelopers.Action
{
    /// <summary>
    /// A class that manages action plug-ins.
    /// </summary>
    public class ActionManager : IActionManager
    {
        private readonly List<IAction> _actions = new List<IAction>();
        private readonly IActionLoader _actionLoader;

        /// <summary>
        /// Initializes a new instance of the <see cref="ActionManager"/> class.
        /// </summary>
        /// <param name="actionLoader">The action loader.</param>
        public ActionManager(IActionLoader actionLoader)
        {
            _actionLoader = actionLoader;
        }

        /// <summary>
        /// Loads the actions.
        /// </summary>
        public void LoadActions()
        {
            // Clear existing actions
            ClearActions();

            // Load
            _actionLoader.Load(this);
        }

        /// <summary>
        /// Clears the actions.
        /// </summary>
        public void ClearActions()
        {
            _actions.Clear();
        }

        /// <summary>
        /// Adds the action.
        /// </summary>
        /// <param name="action">The action.</param>
        public void AddAction(IAction action)
        {
            if(!_actions.Contains(action))
            {
                _actions.Add(action);
            }
        }

        /// <summary>
        /// Gets the actions for the specified target mask.
        /// </summary>
        /// <param name="target">The target mask.</param>
        /// <returns>A list of actions for a given target mask.</returns>
        public IEnumerable<IAction> GetActions(ActionTarget target)
        {
            return _actions.Where(a => (target == (a.Target & target)));
        }
    }
}